package byopenwrt

import (
	"bylib/bylog"
	"fmt"
	"github.com/pkg/errors"
	"io/ioutil"
	"net"
	"strconv"
	"strings"
)

//设置网络参数
func SetNetWork(ifname string,cfg *NetConfig)error{
	bylog.Debug("SetNetWork2=%+v",cfg)
	//var netype="static"
	netcfg:="auto lo\n"
	netcfg=netcfg+"iface lo inet loopback\n"
	netcfg=netcfg+"auto eth0\n"
	netcfg=netcfg+"iface eth0 inet static\n"

	netcfg=netcfg+fmt.Sprintf("address %s\n", cfg.Ip)
	netcfg=netcfg+fmt.Sprintf("netmask %s\n", cfg.Mask)
	netcfg=netcfg+fmt.Sprintf("gateway %s\n", cfg.Gateway)
	return ioutil.WriteFile("/etc/network/interfaces",[]byte(netcfg),0666)
}
//ubus call network.interface.wan status | grep nexthop | grep -oE '([0-9]{1,3}.){3}.[0-9]{1,3}'

func GetNetWorkStatus(ifname string,cfg *NetConfig)error{

	return fmt.Errorf("not support in arm")
}
func GetNetWorkStatus2(ifname string,cfg *NetConfig)error{
	itf,er:=net.InterfaceByName(ifname)
	if er!=nil{
		return er
	}
	addrs,er:=itf.Addrs()
	if er!=nil{
		return er
	}
	if len(addrs) < 1{
		return errors.New("no addr")
	}
	return nil

}
func netmask2string(mask net.IPMask)string{
	val := make([]byte, len(mask))
	copy(val, mask)
	var s []string
	for _, i := range val[:] {
		s = append(s, strconv.Itoa(int(i)))
	}
	return strings.Join(s, ".")
}
//获取某个接口的网络参数
func GetNetWorkConfig(ifname string,cfg *NetConfig)error{

	if err:=CheckNetWorkConfig(cfg);err!=nil{
		return err
	}

	netInterfaces, err := net.InterfaceByName("eth0")
	if err != nil {
		bylog.Error("net.Interfaces failed, err:%s", err.Error())
		return err
	}


	if (netInterfaces.Flags & net.FlagUp) != 0 {
		addrs, _ := netInterfaces.Addrs()

		for _, address := range addrs {
			if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
				if ipnet.IP.To4() != nil {
					cfg.Ip = ipnet.IP.String()
					cfg.Mask = netmask2string(ipnet.Mask)
					cfg.Mac = netInterfaces.HardwareAddr.String()
					g,err:=GetGatewayByIf("eth0")
					if err!=nil{
						bylog.Error("get gateway err=%v",err)
					}
					cfg.Gateway=g
					return nil
				}
			}
		}
	}

	return fmt.Errorf("can not find %s",ifname)

}

//修改wan或者lan接口对应的设备
//ifname 接口名称
//mode wan lan
func ChangeIfDevice(ifname string,device string)error{
	return fmt.Errorf("not support in arm")
}
//修改eth01的mode为lan还是wan
//eth0.2是一个vlan 对应的是以太网的端口0,也就是我们板子上目前使用的口子
//eth0.1是另外一个vlan，对应的是以太网的端口1-4
func ChangeEth02Mode(mode string)error{
	return fmt.Errorf("not support in arm")
}